package com.zhouxin.customview.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import androidx.databinding.adapters.TextViewBindingAdapter.setText
import com.zhouxin.customview.R
import com.zhouxin.customview.extensions.dp2px
import com.zhouxin.customview.extensions.sp2px

/**
 * Copyright©
 * FileName: MultilineView
 * Author: ZhouXin
 * Date: 2022/6/6
 * Description:多行显示的文本（带图片）
 */
private val IMAGE_SIZE = 150.dp2px
private val IMAGE_PADDING = 50.dp2px

class MultilineView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    val text =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lobortis mattis magna eget sollicitudin. Cras sodales erat nibh, eu imperdiet augue congue eu. Donec rutrum sem eros, eu semper urna ultricies sed. Integer non porttitor sem, vitae pharetra sem. Morbi blandit sapien lacus, cursus posuere ex dignissim ut. Mauris ac iaculis ipsum. Phasellus magna neque, dictum et cursus quis, faucibus aliquet ante. Aliquam eu feugiat nulla, a molestie mauris. In vel lacus lectus. Mauris ac pellentesque nisl. Praesent quis nibh tincidunt, consequat nibh ac, dignissim nunc. In ut nibh ultricies enim viverra sagittis. Sed efficitur vestibulum enim nec facilisis.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lobortis mattis magna eget sollicitudin. Cras sodales erat nibh, eu imperdiet augue congue eu. Donec rutrum sem eros, eu semper urna ultricies sed. Integer non porttitor sem, vitae pharetra sem. Morbi blandit sapien lacus, cursus posuere ex dignissim ut. Mauris ac iaculis ipsum. Phasellus magna neque, dictum et cursus quis, faucibus aliquet ante. Aliquam eu feugiat nulla, a molestie mauris. In vel lacus lectus. Mauris ac pellentesque nisl. Praesent quis nibh tincidunt, consequat nibh ac, dignissim nunc. In ut nibh ultricies enim viverra sagittis. Sed efficitur vestibulum enim nec facilisis."

    private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 18.sp2px
    }
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 18.sp2px
    }
    private val bitmap = getAvatar(IMAGE_SIZE.toInt())
    private val fontMetrics = Paint.FontMetrics()

    override fun onDraw(canvas: Canvas) {
        //绘制简单的多行文字（只有文字）
//        val staticLayout =
//            StaticLayout(text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false)
//        staticLayout.draw(canvas)
        //绘制复杂的多行文字
        canvas.drawBitmap(bitmap, width - IMAGE_SIZE, IMAGE_PADDING, paint)
        paint.getFontMetrics(fontMetrics)
        //实际测量单行显示文字的宽度
        val measuredWidth = floatArrayOf(0f)
        //开始位置
        var start = 0
        //计算出的每行的字数
        var count = 0
        //第一排文字的偏移量为:-fontMetrics.top
        var verticalOffset = -fontMetrics.top
        var maxWidth: Float
        while (start < text.length) {
            maxWidth = if (verticalOffset + fontMetrics.bottom < IMAGE_PADDING
                || verticalOffset + fontMetrics.top > IMAGE_PADDING + IMAGE_SIZE
            ) {
                width.toFloat()
            } else {
                width.toFloat() - IMAGE_SIZE
            }
            //通过paint.breakText 测量出每行显示的字数
            count = paint.breakText(text, start, text.length, true, maxWidth, measuredWidth)
            canvas.drawText(text, start, start + count, 0f, verticalOffset, paint)
            start += count
            //paint.fontSpacing：上一行的底部和下一行的底部间的距离
            verticalOffset += paint.fontSpacing
        }
    }

    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(resources, R.drawable.fire_bg, options)
    }
}